#include "draglist.h"

#include <QMimeData>
#include <QDrag>
#include <QMouseEvent>
#include <QApplication>

DragList::DragList(QWidget *parent)
	: QListWidget(parent)
{
	this->setAcceptDrops(true);
	this->setIconSize(QSize(58,58));
}

DragList::~DragList()
{

}

void DragList::startDrag()
{
	QListWidgetItem *item = currentItem();
	if (item) 
	{
		QMimeData *mimeData = new QMimeData;
		mimeData->setText(item->text());
		QDrag *drag = new QDrag(this);
		drag->setMimeData(mimeData);
		drag->setPixmap(QPixmap("./images/move.png"));
		drag->exec(Qt::CopyAction | Qt::MoveAction);
	}
}

void DragList::mousePressEvent( QMouseEvent *event )
{
	if (event->button() == Qt::LeftButton)
		startPos = event->pos();
	QListWidget::mousePressEvent(event);
}

void DragList::mouseMoveEvent( QMouseEvent *event )
{
	if (event->buttons() & Qt::LeftButton) 
	{
		int distance = (event->pos() - startPos).manhattanLength();
		int di = QApplication::startDragDistance();
		if (distance >= QApplication::startDragDistance())
			startDrag();
	}
	QListWidget::mouseMoveEvent(event);
}

void DragList::dropEvent( QDropEvent *event )
{
	DragList *source =
		qobject_cast<DragList *>(event->source());
	if (source && source == this) 
	{
		event->setDropAction(Qt::MoveAction);
		event->accept();
	}
}

void DragList::dragEnterEvent( QDragEnterEvent *event )
{
	DragList *source =
		qobject_cast<DragList *>(event->source());
	if (source && source == this) 
	{
		event->setDropAction(Qt::MoveAction);
		event->accept();
	}
}

void DragList::dragMoveEvent( QDragMoveEvent *event )
{
	DragList *source =
		qobject_cast<DragList *>(event->source());
	if (source && source == this) 
	{
		event->setDropAction(Qt::MoveAction);
		event->accept();
	}
}
